'use client';

import { useState, useEffect, useRef } from 'react';
import { CheckCircle2, Circle, Plus, Trash2, Sparkles, Pencil, X, Check, LogIn, UserPlus, LogOut, User, BarChart3, ImagePlus, Image as ImageIcon } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import Link from 'next/link';
import { createClient } from '@/utils/supabase/client';
import { signOutAction } from '@/app/actions';
import type { User as SupabaseUser } from '@supabase/supabase-js';
import { useRouter } from 'next/navigation';
import type { RealtimePostgresChangesPayload } from '@supabase/supabase-js';

interface Todo {
  id: string;
  user_id: string;
  text: string;
  completed: boolean;
  image_url?: string;
  created_at: string;
  updated_at: string;
}

interface TodoStats {
  total_todos: number;
  completed_todos: number;
  pending_todos: number;
  completion_percentage: number;
}

export default function Home() {
  const [todos, setTodos] = useState<Todo[]>([]);
  const [newTodo, setNewTodo] = useState('');
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editText, setEditText] = useState('');
  const [user, setUser] = useState<SupabaseUser | null>(null);
  const [loading, setLoading] = useState(true);
  const [todoStats, setTodoStats] = useState<TodoStats | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [selectedImage, setSelectedImage] = useState<File | null>(null);
  const [imagePreview, setImagePreview] = useState<string | null>(null);
  const [uploadingImage, setUploadingImage] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const supabase = createClient();
  const router = useRouter();

  // 获取用户的todos
  const fetchTodos = async () => {
    if (!user) return;
    
    try {
      const { data, error } = await supabase
        .from('todos')
        .select('*')
        .order('created_at', { ascending: false });

      if (error) {
        console.error('获取todos失败:', error);
        return;
      }

      setTodos(data || []);
    } catch (error) {
      console.error('获取todos时发生错误:', error);
    }
  };

  // 获取用户统计信息
  const fetchTodoStats = async () => {
    if (!user) return;

    try {
      const { data, error } = await supabase
        .rpc('get_user_todo_stats');

      if (error) {
        console.error('获取统计信息失败:', error);
        return;
      }

      if (data && data.length > 0) {
        setTodoStats(data[0]);
      } else {
        setTodoStats({
          total_todos: 0,
          completed_todos: 0,
          pending_todos: 0,
          completion_percentage: 0
        });
      }
    } catch (error) {
      console.error('获取统计信息时发生错误:', error);
    }
  };

  // 处理实时数据变化
  const handleRealtimeChange = (payload: RealtimePostgresChangesPayload<Todo>) => {
    console.log('Realtime change:', payload);
    
    switch (payload.eventType) {
      case 'INSERT':
        if (payload.new) {
          setTodos(prev => {
            // 检查是否已存在，避免重复添加
            const exists = prev.some(todo => todo.id === payload.new.id);
            if (exists) return prev;
            
            // 按创建时间排序插入
            const newTodos = [payload.new as Todo, ...prev];
            return newTodos.sort((a, b) => 
              new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
            );
          });
          // 更新统计信息
          fetchTodoStats();
        }
        break;
        
      case 'UPDATE':
        if (payload.new) {
          setTodos(prev => prev.map(todo => 
            todo.id === payload.new.id ? payload.new as Todo : todo
          ));
          // 更新统计信息
          fetchTodoStats();
        }
        break;
        
      case 'DELETE':
        if (payload.old) {
          setTodos(prev => prev.filter(todo => todo.id !== payload.old.id));
          // 如果正在编辑被删除的todo，取消编辑
          if (editingId === payload.old.id) {
            setEditingId(null);
            setEditText('');
          }
          // 更新统计信息
          fetchTodoStats();
        }
        break;
    }
  };

  // 设置实时监听
  const setupRealtimeSubscription = () => {
    if (!user) return null;

    const channel = supabase
      .channel('todos-changes')
      .on(
        'postgres_changes',
        {
          event: '*',
          schema: 'public',
          table: 'todos',
          filter: `user_id=eq.${user.id}`
        },
        handleRealtimeChange
      )
      .subscribe((status) => {
        console.log('Realtime subscription status:', status);
      });

    return channel;
  };

  // 上传图片到Supabase Storage
  const uploadImage = async (file: File): Promise<string | null> => {
    if (!user) return null;

    try {
      setUploadingImage(true);
      
      // 生成唯一的文件名
      const fileExt = file.name.split('.').pop();
      const fileName = `${Date.now()}.${fileExt}`;
      const filePath = `${user.id}/${fileName}`;

      // 上传文件到Storage
      const { error: uploadError } = await supabase.storage
        .from('my-todo')
        .upload(filePath, file);

      if (uploadError) {
        console.error('上传图片失败:', uploadError);
        return null;
      }

      // 获取公共URL
      const { data } = supabase.storage
        .from('my-todo')
        .getPublicUrl(filePath);

      return data.publicUrl;
    } catch (error) {
      console.error('上传图片时发生错误:', error);
      return null;
    } finally {
      setUploadingImage(false);
    }
  };

  // 删除Storage中的图片
  const deleteImageFromStorage = async (imageUrl: string) => {
    if (!user || !imageUrl) return;

    try {
      // 从URL中提取文件路径
      const url = new URL(imageUrl);
      const pathParts = url.pathname.split('/');
      const filePath = pathParts.slice(-2).join('/'); // 获取 user_id/filename

      const { error } = await supabase.storage
        .from('my-todo')
        .remove([filePath]);

      if (error) {
        console.error('删除图片失败:', error);
      }
    } catch (error) {
      console.error('删除图片时发生错误:', error);
    }
  };

  // 处理文件选择
  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      alert('请选择图片文件');
      return;
    }

    // 检查文件大小 (5MB)
    if (file.size > 5 * 1024 * 1024) {
      alert('图片大小不能超过5MB');
      return;
    }

    setSelectedImage(file);
    
    // 创建预览
    const reader = new FileReader();
    reader.onload = (e) => {
      setImagePreview(e.target?.result as string);
    };
    reader.readAsDataURL(file);
  };

  // 清除选中的图片
  const clearSelectedImage = () => {
    setSelectedImage(null);
    setImagePreview(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  useEffect(() => {
    // 获取当前用户
    const getUser = async () => {
      const { data: { user } } = await supabase.auth.getUser();
      setUser(user);
      setLoading(false);
    };

    getUser();

    // 监听认证状态变化
    const { data: { subscription } } = supabase.auth.onAuthStateChange(
      (event, session) => {
        setUser(session?.user ?? null);
        setLoading(false);
      }
    );

    return () => subscription.unsubscribe();
  }, [supabase.auth]);

  // 当用户状态改变时，获取todos和统计信息，设置实时监听
  useEffect(() => {
    let realtimeChannel: any = null;

    if (user) {
      fetchTodos();
      fetchTodoStats();
      
      // 设置实时监听
      realtimeChannel = setupRealtimeSubscription();
    } else {
      setTodos([]);
      setTodoStats(null);
    }

    // 清理函数
    return () => {
      if (realtimeChannel) {
        supabase.removeChannel(realtimeChannel);
      }
    };
  }, [user]);

  const addTodo = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // 检查用户是否已登录
    if (!user) {
      router.push('/sign-in');
      return;
    }
    
    if (!newTodo.trim() || isSubmitting) return;

    setIsSubmitting(true);
    try {
      let imageUrl = null;
      
      // 如果有选中的图片，先上传
      if (selectedImage) {
        imageUrl = await uploadImage(selectedImage);
        if (!imageUrl) {
          alert('图片上传失败，请重试');
          setIsSubmitting(false);
          return;
        }
      }

      const { data, error } = await supabase
        .from('todos')
        .insert([
          {
            user_id: user.id,
            text: newTodo.trim(),
            completed: false,
            image_url: imageUrl
          }
        ])
        .select()
        .single();

      if (error) {
        console.error('添加todo失败:', error);
        // 如果数据库插入失败，删除已上传的图片
        if (imageUrl) {
          await deleteImageFromStorage(imageUrl);
        }
        return;
      }

      // 注意：由于实时监听，不需要手动更新本地状态
      // 数据会通过realtime自动同步
      setNewTodo('');
      clearSelectedImage();
      
    } catch (error) {
      console.error('添加todo时发生错误:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  const toggleTodo = async (id: string) => {
    const todo = todos.find(t => t.id === id);
    if (!todo) return;

    try {
      const { error } = await supabase
        .from('todos')
        .update({ completed: !todo.completed })
        .eq('id', id)
        .eq('user_id', user?.id);

      if (error) {
        console.error('更新todo状态失败:', error);
        return;
      }

      // 注意：由于实时监听，不需要手动更新本地状态
      // 数据会通过realtime自动同步
    } catch (error) {
      console.error('更新todo状态时发生错误:', error);
    }
  };

  const deleteTodo = async (id: string) => {
    const todo = todos.find(t => t.id === id);
    if (!todo) return;

    try {
      const { error } = await supabase
        .from('todos')
        .delete()
        .eq('id', id)
        .eq('user_id', user?.id);

      if (error) {
        console.error('删除todo失败:', error);
        return;
      }

      // 如果有图片，删除Storage中的图片
      if (todo.image_url) {
        await deleteImageFromStorage(todo.image_url);
      }

      // 注意：由于实时监听，不需要手动更新本地状态
      // 数据会通过realtime自动同步
    } catch (error) {
      console.error('删除todo时发生错误:', error);
    }
  };

  const startEditing = (todo: Todo) => {
    setEditingId(todo.id);
    setEditText(todo.text);
  };

  const saveEdit = async (id: string) => {
    if (!editText.trim()) return;

    try {
      const { error } = await supabase
        .from('todos')
        .update({ text: editText.trim() })
        .eq('id', id)
        .eq('user_id', user?.id);

      if (error) {
        console.error('更新todo文本失败:', error);
        return;
      }

      // 注意：由于实时监听，不需要手动更新本地状态
      // 数据会通过realtime自动同步
      setEditingId(null);
      setEditText('');
    } catch (error) {
      console.error('更新todo文本时发生错误:', error);
    }
  };

  const cancelEdit = () => {
    setEditingId(null);
    setEditText('');
  };

  const handleSignOut = async () => {
    await signOutAction();
  };

  // 获取用户显示名称（邮箱的用户名部分）
  const getUserDisplayName = (user: SupabaseUser) => {
    if (user.user_metadata?.full_name) {
      return user.user_metadata.full_name;
    }
    if (user.email) {
      return user.email.split('@')[0];
    }
    return '用户';
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-indigo-500 via-purple-500 to-pink-500">
      <div className="max-w-3xl mx-auto p-6">
        {/* Header with Auth Buttons */}
        <div className="flex justify-between items-center mb-6">
          <div></div> {/* Empty div for spacing */}
          <div className="flex gap-3">
            {loading ? (
              <div className="px-4 py-2 bg-white/20 text-white rounded-xl backdrop-blur-lg">
                加载中...
              </div>
            ) : user ? (
              // 已登录状态
              <div className="flex items-center gap-3">
                <div className="inline-flex items-center gap-2 px-4 py-2 bg-white/20 text-white rounded-xl backdrop-blur-lg">
                  <User className="w-4 h-4" />
                  <span>你好，{getUserDisplayName(user)}</span>
                </div>
                <form action={signOutAction}>
                  <button
                    type="submit"
                    className="inline-flex items-center gap-2 px-4 py-2 bg-white/20 hover:bg-white/30 text-white rounded-xl transition-colors duration-200 backdrop-blur-lg"
                  >
                    <LogOut className="w-4 h-4" />
                    退出登录
                  </button>
                </form>
              </div>
            ) : (
              // 未登录状态
              <>
                <Link 
                  href="/sign-in"
                  className="inline-flex items-center gap-2 px-4 py-2 bg-white/20 hover:bg-white/30 text-white rounded-xl transition-colors duration-200 backdrop-blur-lg"
                >
                  <LogIn className="w-4 h-4" />
                  登录
                </Link>
                <Link 
                  href="/sign-up"
                  className="inline-flex items-center gap-2 px-4 py-2 bg-white/20 hover:bg-white/30 text-white rounded-xl transition-colors duration-200 backdrop-blur-lg"
                >
                  <UserPlus className="w-4 h-4" />
                  注册
                </Link>
              </>
            )}
          </div>
        </div>

        <div className="bg-white/10 backdrop-blur-lg rounded-2xl p-8 shadow-xl">
          <div className="flex items-center justify-center mb-8">
            <Sparkles className="w-8 h-8 text-yellow-300 mr-3" />
            <h1 className="text-4xl font-bold text-white">神奇Todo</h1>
          </div>

          {/* 统计信息 */}
          {user && todoStats && (
            <div className="mb-8 p-4 bg-white/10 rounded-xl">
              <div className="flex items-center gap-2 mb-3">
                <BarChart3 className="w-5 h-5 text-yellow-300" />
                <h2 className="text-lg font-semibold text-white">任务统计</h2>
              </div>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-center">
                <div className="bg-white/10 rounded-lg p-3">
                  <div className="text-2xl font-bold text-white">{todoStats.total_todos}</div>
                  <div className="text-sm text-white/70">总任务</div>
                </div>
                <div className="bg-white/10 rounded-lg p-3">
                  <div className="text-2xl font-bold text-green-300">{todoStats.completed_todos}</div>
                  <div className="text-sm text-white/70">已完成</div>
                </div>
                <div className="bg-white/10 rounded-lg p-3">
                  <div className="text-2xl font-bold text-orange-300">{todoStats.pending_todos}</div>
                  <div className="text-sm text-white/70">待完成</div>
                </div>
                <div className="bg-white/10 rounded-lg p-3">
                  <div className="text-2xl font-bold text-blue-300">{todoStats.completion_percentage}%</div>
                  <div className="text-sm text-white/70">完成率</div>
                </div>
              </div>
            </div>
          )}

          <form onSubmit={addTodo} className="mb-8">
            <div className="flex flex-col gap-4">
              <div className="flex gap-2">
                <input
                  type="text"
                  value={newTodo}
                  onChange={(e) => setNewTodo(e.target.value)}
                  placeholder={user ? "添加新任务..." : "登录后添加任务..."}
                  className="flex-1 px-4 py-3 rounded-xl bg-white/20 text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-white/30"
                  disabled={isSubmitting}
                />
                <button
                  type="submit"
                  disabled={isSubmitting || uploadingImage}
                  className="px-6 py-3 bg-white/20 hover:bg-white/30 text-white rounded-xl transition-colors duration-200 flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <Plus className="w-5 h-5" />
                  {isSubmitting ? '添加中...' : '添加'}
                </button>
              </div>
              
              {/* 图片上传区域 */}
              {user && (
                <div className="flex flex-col gap-3">
                  <div className="flex items-center gap-3">
                    <input
                      ref={fileInputRef}
                      type="file"
                      accept="image/*"
                      onChange={handleFileSelect}
                      className="hidden"
                    />
                    <button
                      type="button"
                      onClick={() => fileInputRef.current?.click()}
                      disabled={uploadingImage}
                      className="inline-flex items-center gap-2 px-4 py-2 bg-white/20 hover:bg-white/30 text-white rounded-lg transition-colors duration-200 disabled:opacity-50"
                    >
                      <ImagePlus className="w-4 h-4" />
                      {uploadingImage ? '上传中...' : '添加图片'}
                    </button>
                    {selectedImage && (
                      <button
                        type="button"
                        onClick={clearSelectedImage}
                        className="inline-flex items-center gap-2 px-4 py-2 bg-red-500/20 hover:bg-red-500/30 text-white rounded-lg transition-colors duration-200"
                      >
                        <X className="w-4 h-4" />
                        移除图片
                      </button>
                    )}
                  </div>
                  
                  {/* 图片预览 */}
                  {imagePreview && (
                    <div className="relative w-32 h-32 rounded-lg overflow-hidden bg-white/10">
                      <img
                        src={imagePreview}
                        alt="预览"
                        className="w-full h-full object-cover"
                      />
                    </div>
                  )}
                </div>
              )}
            </div>
          </form>

          <AnimatePresence>
            {todos.map(todo => (
              <motion.div
                key={todo.id}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, x: -100 }}
                className={`flex flex-col gap-3 p-4 mb-3 rounded-xl transition-colors duration-200 ${
                  todo.completed ? 'bg-white/5' : 'bg-white/10'
                }`}
              >
                <div className="flex items-center gap-4">
                  <button
                    onClick={() => toggleTodo(todo.id)}
                    className="text-white hover:text-yellow-300 transition-colors"
                  >
                    {todo.completed ? (
                      <CheckCircle2 className="w-6 h-6" />
                    ) : (
                      <Circle className="w-6 h-6" />
                    )}
                  </button>
                  
                  {editingId === todo.id ? (
                    <div className="flex-1 flex items-center gap-2">
                      <input
                        type="text"
                        value={editText}
                        onChange={(e) => setEditText(e.target.value)}
                        className="flex-1 px-3 py-1 rounded-lg bg-white/20 text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-white/30"
                        autoFocus
                        onKeyDown={(e) => {
                          if (e.key === 'Enter') {
                            saveEdit(todo.id);
                          } else if (e.key === 'Escape') {
                            cancelEdit();
                          }
                        }}
                      />
                      <button
                        onClick={() => saveEdit(todo.id)}
                        className="text-white hover:text-green-400 transition-colors"
                      >
                        <Check className="w-5 h-5" />
                      </button>
                      <button
                        onClick={cancelEdit}
                        className="text-white hover:text-red-400 transition-colors"
                      >
                        <X className="w-5 h-5" />
                      </button>
                    </div>
                  ) : (
                    <>
                      <span
                        className={`flex-1 text-lg text-white ${
                          todo.completed ? 'line-through opacity-50' : ''
                        }`}
                      >
                        {todo.text}
                      </span>
                      {todo.image_url && (
                        <div className="flex items-center gap-2">
                          <ImageIcon className="w-4 h-4 text-white/70" />
                          <span className="text-sm text-white/70">有附件</span>
                        </div>
                      )}
                      <button
                        onClick={() => startEditing(todo)}
                        className="text-white/50 hover:text-blue-400 transition-colors"
                      >
                        <Pencil className="w-5 h-5" />
                      </button>
                      <button
                        onClick={() => deleteTodo(todo.id)}
                        className="text-white/50 hover:text-red-400 transition-colors"
                      >
                        <Trash2 className="w-5 h-5" />
                      </button>
                    </>
                  )}
                </div>
                
                {/* 图片显示 */}
                {todo.image_url && (
                  <div className="ml-10">
                    <img
                      src={todo.image_url}
                      alt="Todo附件"
                      className="max-w-xs max-h-48 rounded-lg object-cover cursor-pointer hover:opacity-80 transition-opacity"
                      onClick={() => window.open(todo.image_url, '_blank')}
                    />
                  </div>
                )}
              </motion.div>
            ))}
          </AnimatePresence>

          {todos.length === 0 && !loading && (
            <div className="text-center text-white/50 py-8">
              {user ? "还没有任务。添加一些任务开始使用吧！" : "登录后制定Todo计划吧！"}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}